<?php

    /**
     * 返回json数据
     */
    function successJson($data,$page = "",$checkCard = ""){
        echo json_encode(array("code"=>0,'message'=>'success','data'=>$data,'page'=>$page,"checkCard"=>$checkCard));
        exit;
    }

    /**
     * 翻页html转换
     */
    function getAjaxPageHtml($pageHtml){

        $pageArr = explode('"',$pageHtml);
        foreach($pageArr AS $pitem){
            if(strstr($pitem,"index.php")){
                $pitemArr = explode("=",$pitem);
                $p = $pitemArr[count($pitemArr)-1];
                $pageHtml = str_replace('"'.$pitem.'"','"javascript:ajax_get_list('.$p.');"',$pageHtml);
            }
        }
       return $pageHtml;
    }

    /**
     * 流量kB转M
     */
     function kbToM($kb){
         return round($kb/1024,2);
     }

    /**
     * 输入M  返回正确的流量
     */
    function mToG($m){
        if($m>=1024){
            $m = round($m/1024,2)."G";
        }else{
            $m = $m."M";
        }
        return $m;
    }

    /**
     * kbto正确的流量值
     */
    function kbToCur($flow){

        if($flow>=1024){
            $flow  = round($flow/1024,2);
            if($flow>1024){
                $flow  = round($flow/1024,2);
                $result = $flow."G";
            }else{
                $result = $flow."M";
            }
        }else{
            $result = $flow."KB";
        }
        return $result;
    }

    /**
     * 写入文件
     */
    function write_file($file_name,$content){
        $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        $fp=fopen("application/Wulian/Cache/".$file_name.".json","w");
        fwrite($fp,$content);
        fclose($fp);
        return true;
    }

    /**
     * 读取文件
     */
    function read_file($file_name){
        $content = file_get_contents("application/Wulian/Cache/".$file_name.".json");
        $content = json_decode($content,true);
        return $content;
    }

    /**
     * 获取文件类型
     */
    function getExcelType(){
        return array("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/octet-stream","application/vnd.ms-excel");
    }

    /**
     * 获取剩余月份
     */
    function getPlusMonth($end_time){
        $e_year = date("Y",$end_time);
        $e_month = date("m",$end_time);
        $n_year = date("Y",time());
        $n_month = date("m",time());

        $result = (($e_year-$n_year)*12)+($e_month-$n_month);
        return $result;
    }

    /**
     * 新增订单
     */
    function addOrder($flow_pool_id,$member_number,$package_id,$order_status = 0,$order_number = "",$openid = "",$source = 1,$is_year = 0,$price = ""){
        if(empty($order_number)){
            $order_number = date("YmdHis").rand(100000,999999);
        }
        $package_type  = array(
            "1"=>"月套餐",
            "2"=>"增量包",
            "3"=>"年续费"
        );
        $m_package = M("WlPackage");
        $m_order = M("WlOrder");
        $m_card = M("WlCard");
        $package = $m_package->where(array("package_id"=>$package_id))->find();
        $package["package_type"] = $is_year?3:$package["package_type"];
        $card = $m_card->where(array("card_number"=>$member_number))->find();
        if(empty($package)|| empty($card)){
            return false;
        }
        $remark = "";
        $last_order = $m_order->where(array("card_number"=>$member_number,"package_type"=>$package["package_type"],"order_status"=>1))->order("create_time DESC")->limit(0,1)->find();
        if(empty($last_order)){
            $last_order["order_price"] = 0;
        }
        if($package["package_type"] == 1){
            $remark .= $package_type[$package["package_type"]]."|".$card["package_data_month"]."M|".$last_order["order_price"]."元 to ";
        }elseif($package["package_type"] == 2){
            $remark .= $package_type[$package["package_type"]]."|".$card["package_data_add"]."M|".$last_order["order_price"]."元 + ";
        }elseif($package["package_type"] == 3){
            $remark .= $package_type[$package["package_type"]]."|".$card["package_data_month"]."M|".$last_order["order_price"]."元 to";
        }

        if(!empty($remark)){
            $remark .= " ".$package_type[$package["package_type"]]."|".$package["package_data"]."M|".$package["package_price"]."元";
        }else{
            $remark .= " 初始套餐 ".$package_type[$package["package_type"]]."|".$package["package_data"]."M|".$package["package_price"]."元";
        }
        if(empty($price)){
            if($is_year){   //年续费
                $price = $package["package_price"]*12;
            }elseif($package["package_type"] == 1){  //月套餐
                $price = getPriceByPackageCard($package,$card);
            }else{
                $price = $package["package_price"];
            }

        }


        $insert = array(
            "order_number"=>$order_number,
            "card_number"=>$member_number,
            "card_iccid"=>$card["card_iccid"],
            "flow_pool_id"=>$flow_pool_id,
            "package_id"=>$package_id,
            "package_data"=>$package["package_data"],
            "package_type"=>$package["package_type"],
            "order_price"=>$price,
            "order_status"=>$order_status,
            "create_time"=>time(),
            "order_remark"=>$remark,
            "order_source"=>$source,
        );

        if($is_year){
            $insert["package_type"] = 3;
        }

        if(!empty($openid)){
            $insert["openid"] = $openid;
        }
        $result = $m_order->add($insert);
        if($result && $order_status == 1){
           successOrder($order_number);
        }
        return $result;
    }

    /**
     * 通过package card 获取到月套餐金额
     */
    function getPriceByPackageCard($package,$card){
        $m_package = M("WlPackage");
        $last_package = $m_package->where(array("package_type"=>1,"package_data"=>$card["package_data_month"]))->find();
        if($last_package['package_data']<$package['package_data']){
            $p_month = getPlusMonth($card['package_endtime']);
            $price = ($package['package_price']-$last_package['package_price'])*($p_month+1);
        }else{
            $price = 0;
        }
        return $price;
    }

    /**
     * 修改流量成功之后
     */
    function successOrder($order_number,$transaction_id = ""){

        $m_order = M("WlOrder");
        $m_card = M("WlCard");
        $m_cron = M("WlCron");
        $m_flow_record = D("WlFlowRecord");

        if(!empty($transaction_id)){
            $m_order->where(array("order_number"=>$order_number))->save(array("order_status"=>1,"transaction_id"=>$transaction_id));
        }

        $order = $m_order->where(array("order_number"=>$order_number))->find();
        $card = $m_card->where(array("card_number"=>$order["card_number"]))->find();
        //插入流量日志记录
        //更新当前卡信息
        if($order['package_type'] == 1){    //月套餐
            $update = array("package_id_month"=>$order["package_id"],"package_data_month"=>$order["package_data"]);
        }elseif($order['package_type'] == 2){   //增量包
            $update = array("package_data_add"=>($card["package_data_add"]+$order["package_data"]));
        }elseif($order["package_type"] == 3){   //年套餐
            $update = array("package_endtime"=>strtotime(date("Y-m-01 00:00:00",$card["package_endtime"])."+13 month")-1,"package_id_month"=>$order["package_id"],"package_data_month"=>$order["package_data"]);
        }
        $result = $m_card->where(array("card_number"=>$order["card_number"]))->save($update);
        if($result && $order['package_type'] == 2){ //购买增量包 插入定时服务 记录截止时间
            $max_day = date("t");
            $cron_insert = array(
                "cron_type"=>1,
                "package_data"=>$order["package_data"],
                "order_id"=>$order["order_id"],
                "cron_plus"=>2,
                "cron_endtime"=>strtotime(date("Y-m-".$max_day." 23:59:59")),
                "card_number"=>$order["card_number"],
            );
            $result = $m_cron->add($cron_insert);
        }
        $m_flow_record->addFlowRecord($order["card_number"]);
        return true;
    }

    /**
     * 添加日志信息
     * 1 导入 2 新增  3修改  4 删除 5充值
     */
    function addLog($type,$content){
        $insert = array(
            "operate_log_uid"=>session("ADMIN_ID"),
            "operate_log_username"=>session("nickname"),
            "operate_log_type"=>$type,
            "operate_log_content"=>$content,
            "operate_log_data"=>json_encode(I('post.'), JSON_UNESCAPED_UNICODE),
            "operate_log_ip"=>get_client_ip(),
        );
        M("WlOperateLog")->add($insert);
    }

    /**
     * 添加定时服务日志
     */
    function addCronLog($type,$content = '',$cost_time = 0){
        if(!empty($content)){
            $insert = array(
                "cron_log_type"=>$type,
                "cron_log_data"=>$content,
                "cron_log_ip"=>get_client_ip(),
                "cron_cost_time"=>$cost_time,
            );
            M("WlCronLog")->add($insert);
        }

    }

    /**
     * 添加流量池充值记录
     */
    function addFlowRechargeLog($data){
        $insert = array(
            "user_id"=>session("ADMIN_ID"),
            "user_nickname"=>session("nickname"),
            "flow_pool_id"=>$data["flow_pool_id"],
            "flow_recharge_plus"=>$data["flow_recharge_plus"],
            "flow_recharge_total"=>$data["flow_recharge_total"],
            "flow_recharge_already"=>$data["flow_recharge_already"],
            "flow_recharge_num"=>$data["flow_recharge_num"],
            "flow_recharge_ip"=>get_client_ip(),
        );
        if($data['cron']){
            $insert["user_id"] = 0;
            $insert["user_nickname"] = "定时服务";
        }
        M('WlFlowRecharge')->add($insert);
    }


    /**
     * 通过ICCID查询卡号
     */
    function getNumberByIccid($iccid){
        $m_card = M("WlCard");
        $card = $m_card->where(array("card_iccid"=>$iccid))->find();
        if(!empty($card)){
            return $card["card_number"];
        }else{
            return false;
        }
    }

    /**
     * 通过卡号 查询ICCID
     */
    function getIccidByNumber($number){
        $m_card = M("WlCard");
        $card = $m_card->where(array("card_number"=>$number))->find();
        if(!empty($card)){
            return $card["card_iccid"];
        }else{
            return false;
        }
    }

    /**
     * 获取当前卡号获取总流量
     */
    function getFlowByCardNumber($card_number){
        $m_card = M("WlCard");
        $card = $m_card->where(array("card_number"=>$card_number))->find();
        if($card){
            return ($card["package_data_month"]+$card["package_data_add"]);
        }else{
            return 0;
        }
    }

    /**
     * 通过ICCID获取总流量
     */
    function getFlowByIccid($iccid){
        $m_card = M("WlCard");
        $card = $m_card->where(array("card_iccid"=>$iccid))->find();
        if($card){
            return ($card["package_data_month"]+$card["package_data_add"]);
        }else{
            return 0;
        }
    }

    /**
     * 通过卡号 获取上月总流量
     */
    function getPreFlowByCardNumber($card_number){
        $m_flow_record = M("WlFlowRecord");
        $cur_time = strtotime(" -1 month ");
        $year = date("Y",$cur_time);
        $month = date("m",$cur_time);
        if($month != 10){
            $month = str_replace('0','',$month);
        }

        $record = $m_flow_record->where(array("card_number"=>$card_number,"flow_record_year"=>$year,"flow_record_month"=>$month))->find();

        if($record){
            return ($record["package_data_month"]+$record["package_data_add"]);
        }else{
            return 0;
        }
    }


    /**
     *查找ICCID是否存在
     */
    function checkCardNumber($card_iccid){
        $m_card = M("WlCard");
        $error_number = "";
        if(is_array($card_iccid)){
            foreach($card_iccid AS $citem){
                $card = $m_card->where(array("card_iccid"=>$citem))->find();
                if(empty($card)){
                    $error_number .= $citem."\\n";
                }
            }
        }else{
            $card = $m_card->where(array("card_iccid"=>$card_iccid))->find();
            if(empty($card)){
                $error_number .= $card_iccid."\\n";
            }
        }

        if(!empty($error_number)){
            echo "<script>alert('{$error_number}此卡还未导入本系统，请确认卡号输入正确后联系管理员初始化导入此卡')</script>";
        }
    }

    /**
     *查找ICCID是否存在
     */
    function checkCardNumberReturnTxt($card_iccid){
        $m_card = M("WlCard");
        $error_number = "";
        $error_message = "";
        if(is_array($card_iccid)){
            foreach($card_iccid AS $citem){
                $card = $m_card->where(array("card_iccid"=>$citem))->find();
                if(empty($card)){
                    $error_number .= $citem."\n";
                }
            }
        }else{
            $card = $m_card->where(array("card_iccid"=>$card_iccid))->find();
            if(empty($card)){
                $error_number .= $card_iccid."\n";
            }
        }

        if(!empty($error_number)){
            $error_message  =  "{$error_number}此卡还未导入本系统，请确认卡号输入正确后联系管理员初始化导入此卡!";
        }
        return $error_message;
    }


    /**
     * 定式服务流量池充值
     * 用户卡充值
     * 错误邮件通知
     */
    function errorEmailAction($title,$content){
        $config_obj = M("WlConfig");
        $error_email_list = $config_obj->field("config_parame,config_value")->where(array("config_parame"=>"error_email"))->find();
        $error_email_list = explode(',',$error_email_list["config_value"]);
        foreach($error_email_list AS $ritem){
            //发送邮箱
            if(!empty($ritem)){
                sp_send_email($ritem, $title, $content);
            }
        }
        return true;
    }





?>